package com.kaifamiao.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet( urlPatterns = "/sign/in", name = "sign-in" )
public class SignInServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.log( String.format( "[%s]正在提供服务", this.toString() ) );
        // 设置从请求中读取数据时使用的字符编码
        request.setCharacterEncoding( "UTF-8" );
        // 设置向响应对象缓冲区输出数据时使用的字符编码
        response.setCharacterEncoding( "UTF-8" );

        /* *** 通过请求对象( request ) 获取请求信息 *** */
        String uname = request.getParameter( "username" );
        String passwd = request.getParameter( "password" );

        // 设置 `响应头` 中的 `content-type` 字段
        // `content-type`: `text/html; charset=UTF-8`
        response.setContentType( "text/html; charset=UTF-8" );

        // 获得向响应对象缓冲区输出数据的字符打印流
        PrintWriter out = response.getWriter();

        if( "kaifamiao".equals( uname ) && "hello".equals( passwd )) {
            out.println( "<h1>欢迎" +uname+ "来到开发喵</h1>" );
            return;
        }

        out.println( "<h1>用户名或密码错误</h1>");

    }

}
